# Replication archive for: Coppock, Alexander and Seth J. Hill and Lynn Vavreck. 2020. "The Small Effects of Political Advertising are Small Regardless of Context, Message, Sender, or Receiver: Evidence from 59 Real-time Randomized Experiments" Science Advances, forthcoming.

library(tidyverse)
library(estimatr)
source("helpers.R")

exps <- read_rds("exps.rds")
ad_df <- read_csv("ad_df.csv")

general <- exps %>% filter(election_phase == "General Election") 

ATEs <-
  bind_rows(
    estimate_ad_effects(general, "general_vote_HC"),
    estimate_ad_effects(general, "general_vote_DT")
  ) %>%
  filter(grepl("ad_id_fac", term)) %>% 
  mutate(ad_id = as.numeric(gsub("ad_id_fac", "", term))) %>%
  left_join(ad_df) %>%
  ungroup %>%
  mutate(
    target_candidate = (
      outcome == "general_vote_DT" & ad_valence %in% c("Pro Trump", "Anti Trump") |
      outcome == "general_vote_HC" & ad_valence %in% c("Pro Clinton", "Anti Clinton")
    ),
    attacking_candidate = 
      (outcome == "general_vote_DT" & ad_valence %in% c("Anti Clinton") |
         outcome == "general_vote_HC" & ad_valence %in% c("Anti Trump")),
    estimate_type = case_when(
      target_candidate ~ "target_candidate",
      attacking_candidate ~ "attacking_candidate",
      TRUE ~ NA_character_
    ),
    attack = as.numeric(grepl("Anti", ad_valence)),
    general = as.numeric(date > as.Date("2016-06-10")),
    pro_clinton = as.numeric(ad_valence == "Pro Clinton"),
    pro_sanders = as.numeric(ad_valence == "Pro Sanders"),
    pro_cruz = as.numeric(ad_valence == "Pro Cruz"),
    pro_kasich = as.numeric(ad_valence == "Pro Kasich"),
    pro_trump = as.numeric(ad_valence == "Pro Trump"),
    
    anti_clinton = as.numeric(ad_valence == "Anti Clinton"),
    anti_trump = as.numeric(ad_valence == "Anti Trump"),
    date_numeric = as.numeric(date) / 365.25,
    attack_d = attack - mean(attack),
    general_d = general - mean(general),
    
    pro_clinton_d = pro_clinton - mean(pro_clinton),
    pro_sanders_d = pro_sanders - mean(pro_sanders),
    pro_trump_d = pro_trump - mean(pro_trump),
    pro_cruz_d = pro_cruz - mean(pro_cruz),
    pro_kasich_d = pro_kasich - mean(pro_kasich),
    anti_clinton_d = anti_clinton - mean(anti_clinton),
    anti_trump_d = anti_trump - mean(anti_trump),
    
    pac = if_else(ad_sponsor %in% c("clinton", "cruz", "sanders", "trump"), 0, 1),
    pac_d = pac - mean(pac),
    
    date_d = date_numeric - mean(date_numeric),
    attack_general_d = attack_d*general_d - mean(attack_d*general_d),
    attack_date_d = attack_d*date_d - mean(attack_d*date_d)
  )

# The recode happens NOW

vote_choice_df <- 
  ATEs %>% 
  filter(target_candidate) %>%
  mutate(
    estimate = if_else(attack == 1, estimate * -1, estimate),
    conf.low = if_else(attack == 1, conf.low * -1, conf.low),
    conf.high = if_else(attack == 1, conf.high * -1, conf.high),
  )

write_rds(vote_choice_df, path = "vote_choice_sates.rds")
